<template lang="pug">
div#MapContainer.map-container
</template>

<script>
import FuMinGEO from '@/assets/data/FuMinGEO.json';
console.log(FuMinGEO)

import {mapGetters, mapMutations} from "vuex";
import Donut from '../../utils/custom-marker';

export default {
  name: "Map",
  data() {
    return {
      map: null,
      arcMap: null,
      geoJSONs: {
        // 富民
        FuMinGEO,
      },
      polygons: {
        FuMin: null,
      },
      labelLayer: null,
      polygonLayer: null,
      GeoJSONLayer: null,
      fullLabelLayer: null,
      visualization: {
        Dot: null,
        Arc: null,
      },
  //     labelsMap: [
		// {
		//    lat: 25.234921853753292,
		//    lng: 102.51924301685449,
		// },
  //       {
  //         lat: 25.345994395506057,
  //         lng: 102.43016570295822,
  //       },
  //       {
  //         lat: 25.31773049858628,
  //         lng: 102.65736893356461,
  //       },
  //       {
  //         lat: 25.372134635340444,
  //         lng: 102.54356466217814,
  //       },
  //       {
  //         lat: 25.44884126844718,
  //         lng: 102.66951144045834,
  //       },
  //       {
  //         lat: 25.54214645886799,
  //         lng: 102.68971217285525,
  //       },
		// {
		//   lat: 25.229223,
		//   lng: 102.53095,
		// },
		
  //     ],
	  labelsMap: [
		{
		   lat: 25.329223,//罗免
		   lng: 102.43095,
		},
	    {
	      
		  lat: 25.31773049858628,
		  lng: 102.65736893356461,//散旦
	    },
	    {
	      lat: 25.372134635340444,//赤鹫
	      lng: 102.54356466217814,
		  // lat: 25.455093,
		  // lng: 102.681404,//款庄
	    },
	    {
	      lat: 25.455093,
	      lng: 102.681404,//款庄
	    },
	    {
	     lat: 25.522979,
	     lng: 102.70774,//东村
	    },
	    {
	      lat: 25.229223,//永定
	      lng: 102.45095,
	    },
		{
		  lat: 25.229223,//大营
		  lng: 102.53095,
		},
	  ],
      polygonGeometries: [],
      markers: [],
      infoWindow: null,
    }
  },
  computed: {
    ...mapGetters({
      mapMarkers: 'map/markers',
      lines: 'map/lines',
      clickCtrl: 'map/clickCtrl',
    }),
  },
  watch: {
    mapMarkers: {
      handler(v) {
        this.renderMarkers(v);
      },
      deep: true,
    },
    '$route.path': {
      handler(nv, ov) {
        this.resetMap(nv);
      },
      deep: true,
    },
  },
  methods: {
    ...mapMutations({
      setPolygonData: 'map/SET_POLYGON_DATA',
      setClickCtrl: 'map/SET_CLICK_CTRL',
    }),
    resetMap() {
      console.log(123);
      this.infoWindow.close();//初始关闭信息窗关闭
      this.clearMarkers();
    },
    renderMap() {
      // 定义地图中心点坐标
      // 25.219667,102.497188
      const center = new this.$TMap.LatLng(25.422245635018015, 102.57200409031157);
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      this.map = new this.$TMap.Map(document.getElementById('MapContainer'), {
        center: center, // 设置地图中心点坐标
        zoom: 11, // 设置地图缩放级别
        doubleClickZoom: false,
        showControl: false,
        scrollable: false,
        draggable: false,
        baseMap: {
          type: 'vector',
          features: ['base'],
        },
        mapStyleId: "style1",
        pitch: 20, // 设置俯仰角
        // rotation: 45 // 设置地图旋转角度
      });




      // FuMinNE 102.78689083522 25.609059812765
      // FuMinSW 102.34756183495 25.133382597971

      // const pxLng = (102.78689083522 - 102.34756183495) / 1070;
      // const pxLat = (25.609059812765 - 25.133382597971) / 1160;
      // const iLng = 102.34756183495 - (pxLng * 681);
      // const iLat = 25.133382597971 - (pxLat * 382);
      // const xLng = 102.78689083522 + (pxLng * 990);
      // const xLat = 25.609059812765 + (pxLat * 338);
      // console.log('123!!!');
      // console.log(iLng, iLat, xLng, xLat);

      // bgNE 102.06795150860992 24.976737170340563
      // bgSW 103.19337280743244 25.747662311558425

      // 背景层底图叠加
      const bgNE = new this.$TMap.LatLng(25.747662311558425, 103.19337280743244);
      const bgSW = new this.$TMap.LatLng(24.976737170340563, 102.06795150860992);
      const bgLatLngBounds = new this.$TMap.LatLngBounds(bgSW, bgNE);
      const bgGroundLayer = new this.$TMap.ImageGroundLayer({
        bounds: bgLatLngBounds,
        src: require('../../assets/images/map.jpg'),
        map: this.map,
        zIndex: 0,
        minZoom: 9,
        maxZoom: 12,
        opacity: 1
      });

      const labelGeometries = [];
      this.polygonGeometries = [];

      // let maxLng = 0;
      // let maxLat = 0;
      // let minLng = 102.44035383505;
      // let minLat = 25.31571410461;

      this.geoJSONs.FuMinGEO.features.forEach((item, index) => {
        const coords = item.geometry.coordinates[0];
        const { name } = item.properties;
        const paths = [];

        coords.forEach(item => {
          const [lng, lat] = item;
          paths.push(new this.$TMap.LatLng(lat, lng));
        });
        const labelLat = this.labelsMap[index].lat,
            labelLng = this.labelsMap[index].lng;
        labelGeometries.push({
          'id': `label-${index}`, //点图形数据的标志信息
          'styleId': 'label', //样式id
          'position': new this.$TMap.LatLng(labelLat, labelLng), //标注点位置
          'content': name, //标注文本
          'properties': { //标注点的属性数据
            'title': 'label'
          }
        });
        this.polygonGeometries.push({
          'id': `polygon-${index}`, //多边形图形数据的标志信息
          'styleId': `normal`, //样式id
          'paths': paths, //多边形的位置信息
          'properties': { //多边形的属性数据
            title: 'polygon',
            ...item.properties,
            simpleName: name,
          }
        });
      });

      // console.log(maxLng, maxLat, minLng, minLat);


      this.labelLayer = new this.$TMap.MultiLabel({
        id: `label-layer`,
        map: this.map,
        styles: {
          'label': new this.$TMap.LabelStyle({
            'color': '#03DDF0', //颜色属性
            'size': 20, //文字大小属性
            'offset': { x: 0, y: 0 }, //文字偏移属性单位为像素
            'angle': 0, //文字旋转属性
            'alignment': 'center', //文字水平对齐属性
            'verticalAlignment': 'middle' //文字垂直对齐属性
          })
        },
        geometries: [...labelGeometries],
      });
      this.polygonLayer = new this.$TMap.MultiPolygon({
        id: `polygon-layer`, //图层id
        map: this.map, //显示多边形图层的底图
        styles: { //多边形的相关样式
          'normal': new this.$TMap.PolygonStyle({
            'color': 'rgba(255, 255, 255, 0.1)', //面填充色
            'showBorder': false, //是否显示拔起面的边线
            'borderColor': '#f00356', //边线颜色
            'borderWidth': '4', //边线颜色
          }),
          'highlight': new this.$TMap.PolygonStyle({
            'color': 'rgba(255, 255, 255, .25)', //面填充色
            'showBorder': false, //是否显示拔起面的边线
            'borderColor': '#f00356', //边线颜色
            'borderWidth': '4', //边线颜色
          }),
        },
        geometries: [...this.polygonGeometries],
      });
      // this.polygonLayer.on('click', res => {
      //   const {geometry} = res;
      //   this.handleAreaClick(geometry);
      // });
      // this.map.on("click", (evt) => {
      //   console.log(evt);
      //   console.log(this.map.getCenter());
      //   console.log(this.map.getZoom());
      //   // this.map.setCenter(new this.$TMap.LatLng(evt.latLng.lat, evt.latLng.lng));
      // });

      this.infoWindow = new this.$TMap.InfoWindow({
        map: this.map,
        position: new this.$TMap.LatLng(25.422245635018015, 102.57200409031157),
        offset: { x: 0, y: -80 }, //设置信息窗相对position偏移像素，为了使其显示在Marker的上方
        zIndex: 9
      });
      this.infoWindow.close();//初始关闭信息窗关闭
    },
    handleAreaClick(geometry) {
      this.polygonGeometries.map(item => {
        item.styleId = 'normal';
      });
      const targetIndex = this.polygonGeometries.findIndex(item => item.id === geometry.id);
      this.polygonGeometries.splice(targetIndex, 1, {
        ...geometry,
        styleId: 'highlight',
      });
      this.polygonLayer.updateGeometries([
        ...this.polygonGeometries,
      ]);
      // targetGeometry
      this.setPolygonData(geometry);
      this.setClickCtrl({
        ...geometry,
      });
    },
    handleAreaAll() {
      this.polygonGeometries.map(item => {
        item.styleId = 'normal';
      });
      this.polygonLayer.updateGeometries([
        ...this.polygonGeometries,
      ]);
      this.setPolygonData({
        'id': `polygon-DeHong`, //多边形图形数据的标志信息
        'styleId': `normal`, //样式id
        'paths': [], //多边形的位置信息
        'properties': { //多边形的属性数据
          title: 'polygon',
          ...this.geoJSONs.DeHongGEO.features[0].properties,
          simpleName: '德宏州',
        }
      })
    },
    renderMarkers(markerList) {
      // debugger
      if (markerList.length > 0) {
        this.clearMarkers();
        markerList.forEach(marker => {
          const finalMarker = new Donut({
            map: this.map,
            position: new this.$TMap.LatLng(marker.lat, marker.lng),
            data: {
              label: marker.label,
              name: marker.name,
              desc: marker.desc,
              product: marker.product,
            }
          });
          finalMarker.on('click', () => {
            console.log(123);
            console.log(finalMarker);

            this.infoWindow.open(); //打开信息窗
            this.infoWindow.setPosition(finalMarker.position);//设置信息窗位置
            this.infoWindow.setContent(
    `<div class="custom-info-window">
              <h3>${finalMarker.data.name}</h3>
              <p>${finalMarker.data.desc}</p>
              <p>${finalMarker.data.product}</p>
            </div>`);//设置信息窗内容
          });
          this.markers.push(finalMarker);
        });
        // this.markers.forEach(marker => {
        //   console.log(marker);
        //   marker.on('click', () => {
        //     console.log(123);
        //   })
        // })
      } else {
        this.clearMarkers();
      }
    },
    clearMarkers() {
      this.markers.forEach(item => {
        item.destroy();
      });
      this.markers = [];
    },
    initMap(pathVal) {
      this.renderMap();
    }
  },
  mounted() {
    this.initMap();
  }
}
</script>

<style lang="scss" scoped>
.map-container{
  @extend %abs-full;
  z-index: 0;
  color: rgba(0, 204, 135, 0.3);
}
</style>
